<!-- 实体模型 -->
<script lang="ts" setup>
import type { FormInstance } from "element-plus"
import { usePagination } from "@@/composables/usePagination"
import { Loading, Search } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue"
import { useRouter } from "vue-router"
import ScenarioCard from "./components/ScenarioCard.vue"
import { searchThreeDataApi, deleteThreeDataApi } from "@@/apis/Three-model"
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh";
import upload from "@@/components/SelectThreeMilstd/upload.vue"

defineOptions({
  // 命名当前组件
  name: "ThreeModel"
})

const router = useRouter()
const searchFormRef = ref<FormInstance | null>(null)
const searchKey = ref()
const loading = ref<boolean>(false)
const tableData = ref([])
const multipleSelection = ref([])
const TableRef = ref()
const showThreeModel = ref(false)
const { paginationData } = usePagination()
const isDetail = ref(false)
paginationData.pageSize = 20

// 无限滚动状态
const isLoading = ref(false)
const hasMoreData = ref(true)
// 计算属性：选中的ID列表

// 搜索表单数据
const searchData = reactive({
  pageNum: 0,
  pageSize: 20,
})

// 修改卡片容器引用
const cardScrollContainer = ref()
const refreshKey = ref(0)
const detailId = ref('')
// 获取表格数据（首次加载或搜索）
function getTableData() {
  // 重置状态
  hasMoreData.value = true
  paginationData.currentPage = 1

  const params = buildRequestParams()

  loading.value = true
  return searchThreeDataApi(params)
    .then(({ data }) => {
      // 检查是否还有更多数据
      hasMoreData.value = data.rows.length >= paginationData.pageSize

      // 更新表格数据
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
      hasMoreData.value = false
    })
    .finally(() => {
      loading.value = false

      // 检查是否需要立即加载更多
      checkAndLoadMore()
    })
}

// 构建请求参数
function buildRequestParams() {
  const params = {
    pageSize: paginationData.pageSize,
    pageNum: paginationData.currentPage,
    searchKey: searchKey.value
  }

  return params
}

// 检查并加载更多数据（如果内容不足以滚动）
function checkAndLoadMore() {
  nextTick(() => {
    cardScrollContainer.value = document.querySelector(".custom-card-container")
    const isScrollable = cardScrollContainer.value.scrollHeight > cardScrollContainer.value.clientHeight
    if (!isScrollable && hasMoreData.value) {
      loadData()
    }
  })
}

// 搜索处理
function handleSearch() {
  if (paginationData.currentPage === 1) {
    getTableData()
  } else {
    paginationData.currentPage = 1
  }
}
// 实体详情或创建
function handleCreateTask() {
  showThreeModel.value = !showThreeModel.value
  isDetail.value = true
}
// 批量删除
function handleMultipleDelete() {
  if (!multipleSelection.value.length) return

  const ids = multipleSelection.value.map(item => item.id as string)
  const names = multipleSelection.value.map(item => item.name)
  confirmDelete(names.join("，"), () => {
    deleteThreeDataApi(ids).then(() => {
      ElMessage.success("删除成功")
      multipleSelection.value = []
      getTableData()
      // 强制刷新视图
    refreshKey.value += 1
    })
  })
}

// 删除单个实体
function handleDelete(row: any) {
  if (!row.id) return
  confirmDelete(row.name, () => {
    deleteThreeDataApi([row.id]).then(() => {
      ElMessage.success("删除成功")
      multipleSelection.value = []
      getTableData()
      // 强制刷新视图
    refreshKey.value += 1
    })
  })
}

// 删除确认
function confirmDelete(name: string, callback: () => void) {
  ElMessageBox.confirm(`正在删除三维模型：${name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(callback)
}

// 查看详情
function handleView(row: any) {
  detailId.value = row.id
  isDetail.value = false
  showThreeModel.value = true
}

// 切换选择
function handleToggleSelect(row: any) {
  // 检查项目是否已在选择列表中
  const existingIndex = multipleSelection.value.findIndex(item => item.id === row.id);

  if (existingIndex !== -1) {
    // 如果已存在，则从选择列表中移除
    multipleSelection.value.splice(existingIndex, 1);
  } else {
    // 如果不存在，则添加到选择列表
    multipleSelection.value.push(row);
  }
}

// 添加卡片滚动处理函数
function handleCardScroll() {
  if (!cardScrollContainer.value) return

  const {
    scrollTop,
    scrollHeight,
    clientHeight
  } = cardScrollContainer.value

  // 当距离底部 100px 时触发加载
  if (scrollHeight - scrollTop - clientHeight <= 100) {
    loadData()
  }
}
useAutoRefresh(handleSearch)
// 修改 onMounted 钩子，确保正确获取卡片容器
onMounted(() => {
  handleSearch()

  // 为表格添加滚动监听
  nextTick(() => {
    cardScrollContainer.value.addEventListener("scroll", handleCardScroll)
  })
})

// 修改 loadData 函数，确保返回 Promise
function loadData() {

  // 防止重复加载
  if (isLoading.value || !hasMoreData.value) {
    return Promise.resolve()
  }

  isLoading.value = true
  paginationData.currentPage++

  const params = buildRequestParams()

  return searchThreeDataApi(params)
    .then(({ data }) => {

      // 检查是否还有更多数据
      hasMoreData.value = data.rows.length >= paginationData.pageSize

      // 追加新数据
      tableData.value = [...tableData.value, ...data.rows]

      // 更新总数
      paginationData.total = data.total
    })
    .catch((error) => {
      hasMoreData.value = false
    })
    .finally(() => {
      isLoading.value = false
      checkAndLoadMore()
      return Promise.resolve()
    })
}

// 无限滚动配置
const infiniteScrollConfig = {
  // 距离底部多少像素时触发加载
  distance: 100,
  // 是否禁用
  disabled: computed(() => isLoading.value || !hasMoreData.value),
  // 立即检查
  immediate: true
}

// 新增三维模型
const handleCloseUpload = () => {
  showThreeModel.value = false
  isDetail.value = false
  getTableData()
}

onUnmounted(() => {
  if (cardScrollContainer.value) {
    cardScrollContainer.value.removeEventListener("scroll", handleCardScroll)
  }
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-form ref="searchFormRef" :model="searchData" size="large" :inline="true" @keyup.enter="handleSearch">
          <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input"
            @keydown.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" v-throttle="() => handleSearch()" />
            </template>
          </el-input>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding toolbar">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask">
            新增三维模型
          </el-button>
          <el-button :disabled="multipleSelection.length < 1" type="danger" @click="handleMultipleDelete">
            批量删除
          </el-button>
        </div>
      </div>
      <div class="cpi-content-main">
        <div class="custom-card-container" ref="cardScrollContainer" :key="refreshKey" v-infinite-scroll="loadData"
          :infinite-scroll-disabled="infiniteScrollConfig.disabled"
          :infinite-scroll-distance="infiniteScrollConfig.distance"
          :infinite-scroll-immediate="infiniteScrollConfig.immediate">
          <template v-for="(item, index) in tableData" :key="index">
            <ScenarioCard :data="item" @handle-delete="handleDelete" @handle-view="handleView"
              @toggle-select="handleToggleSelect" />
          </template>
          <div class="card-loading-indicator">
            <div v-if="isLoading" class="loading-more">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
              <span>加载中...</span>
            </div>
            <div v-else-if="hasMoreData" class="loading-more">
              <i class="fas fa-angle-double-down el-icon" />
              <span>下拉加载更多数据...</span>
            </div>
            <div v-else-if="!hasMoreData && tableData.length > 0" class="no-more-data">
              <span>没有更多数据了</span>
            </div>
            <div v-else-if="tableData.length === 0" class="no-data">
              <span>暂无数据</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <upload :visible="showThreeModel" detailName="" :id="detailId" :isDetail="isDetail" accept=".glb, .fbx, .gltf, .obj, .stl, .3ds"
      type="three-model" @close-dialog="handleCloseUpload"></upload>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/main-page.scss";
@import "@@/assets/styles/mixins.scss";

.cc-search-common {
  .el-form-item--large {
    margin-bottom: 0px !important;
  }
}

.toolbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.sh-operate {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  overflow: hidden;

  .tab {
    flex: 1;
    overflow: hidden;
    display: flex;
    justify-content: flex-end;
  }

  .demo-tabs {
    max-width: 500px;
  }
}

:deep(.el-tabs__item) {
  padding: 0 10px !important;
}

:deep(.el-tabs__header) {
  margin: 0 !important;
}

:deep(.el-tabs__item.is-active),
:deep(.el-tabs__item:hover) {
  color: #00f3c7 !important;
}

:deep(.el-tabs__nav-wrap:after),
:deep(.el-tabs__active-bar) {
  display: none !important;
}

.custom-card-container {
  $border-color: #223448;
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  padding: 5px 10px 0px 0 !important;
}

.custom-card-container>* {
  min-width: 0;
}

.pager-container {
  padding-bottom: 20px !important;
}

.loading-more,
.no-more-data {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;

  .el-icon {
    margin-right: 8px;
  }
}

.no-more-data {
  color: #c0c4cc;
}

/* 修改卡片视图的加载指示器样式 */
.card-loading-indicator {
  grid-column: 1 / -1;
  height: 50px;
  padding: 20px 0;
  text-align: center;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;

  .loading-more,
  .no-more-data,
  .no-data {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 14px;

    .el-icon {
      margin-right: 8px;
    }
  }

  .no-more-data,
  .no-data {
    color: #c0c4cc;
  }
}

/* 优化卡片容器样式 */
.custom-card-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  padding: 10px;
  min-height: 100%;
  /* 确保容器至少填满父元素 */
}

@media screen and (max-width: 768px) {
  .toolbar {
    flex-direction: column;
  }
}
</style>
